import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { MapAreaEntity } from "../entities/map-area.entity";

@Injectable()
export class MapAreaService {
  constructor(
    @InjectRepository(MapAreaEntity)
    private mapAreaRepo: Repository<MapAreaEntity>
  ) {}

  /**
   * 根据区域ID获取区域信息
   */
  async getAreaById(areaId: number): Promise<MapAreaEntity | null> {
    return this.mapAreaRepo.findOne({ where: { id: areaId } });
  }

  /**
   * 根据父级ID获取子区域列表
   */
  async getSubAreasByParentId(parentId: number): Promise<MapAreaEntity[]> {
    return this.mapAreaRepo.find({
      where: { parentId },
      order: { id: "ASC" },
    });
  }

  /**
   * 获取所有顶级区域（没有父级的区域）
   */
  async getTopLevelAreas(): Promise<MapAreaEntity[]> {
    return this.mapAreaRepo.find({
      where: { parentId: undefined },
      order: { id: "ASC" },
    });
  }

  /**
   * 根据区域ID获取区域及其子区域
   */
  async getAreaWithSubAreas(areaId: number): Promise<{
    area: MapAreaEntity | null;
    subAreas: MapAreaEntity[];
  }> {
    const [area, subAreas] = await Promise.all([
      this.getAreaById(areaId),
      this.getSubAreasByParentId(areaId),
    ]);

    return { area, subAreas };
  }

  /**
   * 批量获取区域信息
   */
  async getAreasByIds(areaIds: number[]): Promise<MapAreaEntity[]> {
    if (areaIds.length === 0) return [];
    return this.mapAreaRepo.findByIds(areaIds);
  }
}
